package com.linln.admin.SpringBoot.controller;

import com.linln.admin.SpringBoot.domain.Lab;
import com.linln.admin.SpringBoot.domain.Lock;
import com.linln.admin.SpringBoot.service.LabService;
import com.linln.admin.SpringBoot.service.LockService;
import com.linln.admin.SpringBoot.validator.LockValid;
import com.linln.common.enums.StatusEnum;
import com.linln.common.utils.EntityBeanUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.StatusUtil;
import com.linln.common.vo.ResultVo;
import com.linln.modules.system.domain.User;
import com.linln.modules.system.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * @author Airili
 * @date 2020/12/22
 */
@Controller
@RequestMapping("/SpringBoot/lock")
public class LockController {

    @Autowired
    private LockService lockService;
    @Autowired
    private UserService userService;
    @Autowired
    private LabService labService;
    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("SpringBoot:lock:index")
    public String index(Model model, Lock lock) {

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("lab_id", match -> match.contains());

        // 获取数据列表
        Example<Lock> example = Example.of(lock, matcher);
        Page<Lock> list = lockService.getPageList(example);

        List<Lock> locks = list.getContent();
        System.out.println(locks.size());
        for(int i = 0;i<locks.size();i++){
            String labName = labService.getById(locks.get(i).getLab_id()).getName();
            User user = userService.getById(locks.get(i).getUser_id());
            locks.get(i).setPowerName(user.getNickname());
            locks.get(i).setUsername(user.getUsername());
            locks.get(i).setLabName(labName);
        }
        List<Lab> labs = labService.findAll();
        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        model.addAttribute("labs",labs);
        return "/SpringBoot/lock/index";
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    @RequiresPermissions("SpringBoot:lock:add")
    public String toAdd(Model model) {
        List<Lab> labs = labService.findAll();
        model.addAttribute("labs",labs);
        return "/SpringBoot/lock/add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("SpringBoot:lock:edit")
    public String toEdit(@PathVariable("id") Lock lock, Model model) {
        List<Lab> labs = labService.findAll();
        lock.setUsername(userService.getById(lock.getUser_id()).getUsername());
        model.addAttribute("lock", lock);
        model.addAttribute("labs",labs);
        model.addAttribute("lab_id",lock.getId());
        return "/SpringBoot/lock/add";
    }

    /**
     * 保存添加/修改的数据
     * @param valid 验证对象
     */
    @PostMapping("/save")
    @RequiresPermissions({"SpringBoot:lock:add", "SpringBoot:lock:edit"})
    @ResponseBody
    public ResultVo save(@Validated LockValid valid, Lock lock) {
        lock.setUser_id(userService.getByName(lock.getUsername()).getId());
        // 复制保留无需修改的数据
        if (lock.getId() != null) {
            Lock beLock = lockService.getById(lock.getId());
            EntityBeanUtil.copyProperties(beLock, lock);
        }

        // 保存数据
        lockService.save(lock);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("SpringBoot:lock:detail")
    public String toDetail(@PathVariable("id") Lock lock, Model model) {
        String labName = labService.getById(lock.getLab_id()).getName();
        lock.setUsername(userService.getById(lock.getUser_id()).getUsername());
        lock.setPowerName(userService.getById(lock.getUser_id()).getNickname());
        lock.setLabName(labName);
        model.addAttribute("lock",lock);
        return "/SpringBoot/lock/detail";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @RequiresPermissions("SpringBoot:lock:status")
    @ResponseBody
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if (lockService.updateStatus(statusEnum, ids)) {
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
        } else {
            return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
        }
    }
}